package com.godtree.util;

import cn.hutool.core.lang.func.VoidFunc;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailUtil;
import com.godtree.properties.MailProperties;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author lisicheng
 * @date 20220726
 */
@Component
public class WranMsgUtils implements InitializingBean {

  @Value("${spring.profiles.active}")
  private String profileActive;

  @Value("${wran.type:dingtalk}")
  private String wranType;

  private static String PROFILE_ACTIVE;

  private static String WRAN_TYPE;

  private final static Map<String, VoidFunc<String>> MSG_MAP = ImmutableMap.<String, VoidFunc<String>>builder()
      .put("mail",
          param -> MailUtil.send(MailProperties.getMailProperties().getTo(),
              StrUtil.format("【{}】{}", PROFILE_ACTIVE, param[0]), param[1], false))
      .put("dingtalk",
          param -> DingtalkUtil.send(StrUtil.format("【{}】{}", PROFILE_ACTIVE, param[0]), param[1]))
      .build();

  /**
   * 单例线程池
   */
  @SuppressWarnings("all")
  private final static Executor EXECUTOR = Executors.newSingleThreadExecutor();

  public static void send(String title, String content) {
    EXECUTOR.execute(() -> {
      MSG_MAP.get(WRAN_TYPE).callWithRuntimeException(title, content);
    });
  }


  @Override
  public void afterPropertiesSet() throws Exception {
    PROFILE_ACTIVE = profileActive;
    WRAN_TYPE = wranType;
  }
}
